<?php

namespace app\api\controller\wanlshop;

use app\common\controller\Api;
use app\admin\model\wanlshop\AgentOrder;
use app\api\model\wanlshop\Order;
use app\admin\model\wanlshop\Agent as agentModel;

class Agent extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function info()
    {
        $user_id = $this->auth->id;
        $user = \app\common\model\User::field(['id', 'avatar', 'username', 'nickname'])->find(['id' => $user_id]);
        $agent = agentModel::where('user_id', $user_id)->find();
        if ($agent) {
            $agent['total'] = bcadd($agent['waitting'] ?? 0, $agent['amount'] ?? 0, 2);
            $agent['bi'] = AgentOrder::where(['parent_agent_id' => $agent['id'], 'status' => 1])->count();
        }
        $this->success('返回成功', [
            'user' => $user,
            'agent' => $agent
        ]);
    }

    public function apply()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $level = 1;
            $model = agentModel::where('user_id', $this->auth->id)->find();

            $exist = null;
            if ($model) {
                if ($model['status'] != 2) {
                    $this->error(__('不能重复申请'));
                }
                /*if ($level == 1) {
                    $exist = agentModel::where('address', $data['data']['address'])
                        ->where('id', '<>', $model['id'])
                        ->where('level', '<>', $level)
                        ->where('status', 1)
                        ->find();
                }*/
            } else {
                $shop = \app\api\model\wanlshop\Shop::where('user_id', $this->auth->id)->find();
                $model = new agentModel();
                $model->user_id = $this->auth->id;
                $model->parent_id = $shop ? $shop['agent_id'] : 0;

                /*if ($level == 1) {
                    $exist = agentModel::where('address', $data['data']['address'])
                        ->where('status', 1)
                        ->where('level', '<>', $level)
                        ->find();
                }*/
            }
            /*if ($exist) {
                $this->error(__('当前区域已有代理商'));
            }*/

            if (!empty($data['data']['inv_code'])) {
                $a = agentModel::where('code', $data['data']['inv_code'])->find();
                if (!$a) {
                    $this->error(__('邀请码不存在'));
                }
                $model->parent_id = $a ? $a['id'] : 0;
                $level = 2;
            }

            $model->realname = $data['data']['realname'];
            $model->account = $data['data']['account'];
            $model->address = $data['data']['address'];
            $model->level = $level;
            $model->id_frontend = $data['data']['id_frontend'];
            $model->id_backend = $data['data']['id_backend'];
            $model->mobile = $data['data']['mobile'];
            $model->id_number = $data['data']['id_number'];
//            $model->parent_id = !empty($a) ? $a['id'] : 0;
            $model->status = 0;
            $model->save();
            $this->success('申请成功');
        }
        $this->error(__('非法请求'));
    }

    public function list()
    {
        $id = $this->request->get('id', 0);
        $model = agentModel::where('user_id', $this->auth->id)->find();
        $target = $id ?: $model['id'];
        $list = AgentOrder::where(['parent_agent_id' => $target, 'status' => 1])
            ->with(['agent', 'user',
                'order.realstore'
            ])
            ->order('id', 'desc')
            ->paginate(10);
        foreach ($list as $key => $item) {
            if (!$item->user) {
                unset($list[$key]);
            }
        }
        $list = $list->toArray();
        $list['data'] = array_values($list['data']);
        $this->success('获取成功', $list);
    }

    public function partner()
    {
        $uid = $this->auth->id;
        $size = $this->request->get('pageSize');
        $info = agentModel::where('user_id', $uid)->find();
        $list = [];
        if ($info) {
            $ids = agentModel::where('parent_id', $info['id'])->column('id');
            $list = \app\api\model\wanlshop\Shop::where('agent_id', 'in', array_merge($ids, [$info['id']]))
                ->order('id', 'desc')->select();
        }
        $res = [];
        if ($list) {
            foreach ($list as &$item) {
                $item['agent'] = agentModel::find($item['agent_id']);
                $item['amount'] = $this->getAmount($item['id']);
                $res[] = $item;
            }
        }
        $this->success('获取成功', array_values(array_unique(array_column($res, null, 'id'))));
    }

    private function getAmount($sid)
    {
        $order = Order::where('real_store_id', $sid)->with('pay')
            ->where('state', 'in', [2, 3, 4, 6])->select() ?? [];
        if ($order) {
            $amount = 0;
            foreach ($order as $item) {
                $amount += $item['pay']['price'];
            }
            return number_format($amount, 2, '.', '');
        } else {
            return 0;
        }
    }

    public function pay_log()
    {
        $id = $this->request->get('id');
        $size = $this->request->get('pageSize', 10);
        $list = Order::where('real_store_id', $id)->alias('order')
            ->where('state', 'in', [2, 3, 4, 6])
            ->with([
                'user' => function ($query) {
                    $query->field(['username', 'nickname', 'avatar']);
                },
                'pay' => function ($query) {
                    $query->field(['id', 'price', 'order_id']);
                },
                'realstore' => function ($query) {
                    $query->field(['id', 'shopname']);
                }
            ])
            ->order('order.id', 'desc')
            ->paginate($size);
        $this->success('获取成功', $list);
    }

    public function children()
    {
        $uid = $this->auth->id;
        $size = $this->request->get('pageSize');
        $info = agentModel::where('user_id', $uid)->find();
        $this->success('获取成功', array_values($this->getChildren($info['id'])));
    }

    private function getChildren($id, &$res = [])
    {
        $s = agentModel::where('parent_id', $id)->with('user')->order('id', 'desc')->select();
        if ($s) {
            foreach ($s as $item) {
                if (!$item->user) {
                    continue;
                }
                $res[] = $item;
                $this->getChildren($item['id'], $res);
            }
        }
        return $res;
    }
}